package com.pacvue.interceptor;

import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pacvue.entity.RequestLog;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class RequestLogInterceptor implements HandlerInterceptor {

    private static final ThreadLocal<Long> START_TIME = new InheritableThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        START_TIME.set(System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Long startTime = START_TIME.get();
        RequestLog log = RequestLog.builder()
            .url(request.getRequestURL().toString())
            .method(request.getMethod())
            .requestParams(getRequestParams(request))
            .build();


        long endTime = System.currentTimeMillis();

    }

    private String getRequestParams(HttpServletRequest request) {
        String method = request.getMethod();
        String contentType = request.getHeader("Content-Type");
        try {
            if ("GET".equalsIgnoreCase(method) || "DELETE".equalsIgnoreCase(method)) {
                return request.getQueryString();
            } else if ("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method)) {
                if (contentType.contains("application/json")) {
                    return new ObjectMapper().writeValueAsString(request.getParameterMap());
                } else if (contentType.contains("application/x-www-form-urlencoded")) {
                    Map<String, String[]> parameterMap = request.getParameterMap();
                    return new ObjectMapper().writeValueAsString(parameterMap);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return null;
//        try {
//            Map<String, String[]> paramMap = request.getParameterMap();
//            return new ObjectMapper().writeValueAsString(paramMap);
//        } catch (Exception e) {
//            return "{}";
//        }
    }

    private String getClientIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        return ip != null ? ip.split(",")[0] : request.getRemoteAddr();
    }

    private void logRequest(RequestLog log) {
        // 可以替换成写数据库、发MQ、打印JSON、送到ELK等
        System.out.println("请求日志：" + log);
    }
}
